//
//  NetworkTool.m
//  Medicine
//
//  Created by Just-h on 16/5/30.
//  Copyright © 2016年 JUST-Hychen. All rights reserved.
//

#import "NetworkTool.h"
#import "TypeDef.h"

@implementation NetworkTool
+ (instancetype)sharedNetworkTool {
    static id instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    
    return instance;
}


/**
 *  通用请求数据接口,有Token(记录类型)
 *
 *  @param params  参数数组
 *  @param success 成功回调
 *  @param failure 失败回调
 */
- (void)requestDataWithParams:(NSArray *)params authType:(AuthModel)authType dataType:(DataType)dataType Success:(void (^)(id obj))success Failure:(void (^)(NSString *code,NSString *msg))failure{
    // 初始化请求体(params[0] -> 命令代码)
    NSArray *codeArray = [params[0] componentsSeparatedByString:@"/"];
    NSString *funcCode = [codeArray lastObject];
    [MessageFactory getAppConfig].appcode = [codeArray firstObject];
    RequestMessage *req = [[RequestMessage alloc] initWithFunc:funcCode];
    req.header.httpheader.device_token = [[NSUserDefaults standardUserDefaults] objectForKey:App_DeviceToken_Key];
    NSLog(@"%@,,,%@",req.header.httpheader.username,req.header.httpheader.password);
    req.header.datatype = dataType;
    [MessageFactory getHttpHeader].authtype = authType;
    switch (params.count) {
        case 2:
            [req.body setItemParaListWithIndex:params[1], nil];
            break;
        case 3:
            [req.body setItemParaListWithIndex:params[1],params[2], nil];
            break;
        case 4:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3], nil];
            break;
        case 5:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4], nil];
            break;
        case 6:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5], nil];
            break;
        case 7:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6], nil];
            break;
        case 8:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7], nil];
            break;
        case 9:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8], nil];
            break;
        case 10:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9], nil];
            break;
        case 11:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10], nil];
            break;
        case 12:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11], nil];
            break;
        case 13:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11],params[12], nil];
            break;
        case 14:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11],params[12],params[13], nil];
            break;
        case 15:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11],params[12],params[13],params[14], nil];
            break;
        case 16:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11],params[12],params[13],params[14],params[15], nil];
            break;
        case 17:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11],params[12],params[13],params[14],params[15],params[16], nil];
            break;
        case 18:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11],params[12],params[13],params[14],params[15],params[16],params[17], nil];
            break;
        case 19:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11],params[12],params[13],params[14],params[15],params[16],params[17],params[18], nil];
            break;
        case 20:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11],params[12],params[13],params[14],params[15],params[16],params[17],params[18],params[19], nil];
            break;
        default:
            break;
    }
    WeakSelf_bb
    req.header.httpheader = [MessageFactory getHttpHeader];
    [MessageFactory doPost:req httpresult:^(ResponseMessage *res) {
        NSString *status = res.header.status;
        if ([status isEqualToString:@"200"]) {

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            success(res.body.data);
        }
        else{
            if (res.header.info) {
                self.failInfo = res.header.info;
            }
            
            if (![status isEqualToString:@"309"]) {
                NSString *failInfo = self.failInfo ? self.failInfo : @"请求失败";
                Show_Msg_Error(failInfo)
            }else{
                self.failInfo = nil;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    Dismiss_NoMsg
                });
            }
            failure(status,weakSelf.failInfo);
        }
    }];
}


/**
 *  通用请求数据接口,有Token(记录类型)
 *
 *  @param params  参数数组
 *  @param success 成功回调
 *  @param failure 失败回调
 */
- (void)requestDataNoMessageWithParams:(NSArray *)params authType:(AuthModel)authType dataType:(DataType)dataType Success:(void (^)(id obj))success Failure:(void (^)(NSString *code,NSString *msg))failure{
    // 初始化请求体(params[0] -> 命令代码)
    NSArray *codeArray = [params[0] componentsSeparatedByString:@"/"];
    NSString *funcCode = [codeArray lastObject];
    [MessageFactory getAppConfig].appcode = [codeArray firstObject];
    RequestMessage *req = [[RequestMessage alloc] initWithFunc:funcCode];
    req.header.httpheader.device_token = [[NSUserDefaults standardUserDefaults] objectForKey:App_DeviceToken_Key];
    NSLog(@"%@,,,%@",req.header.httpheader.username,req.header.httpheader.password);
    req.header.datatype = dataType;
    [MessageFactory getHttpHeader].authtype = authType;
    req.header.httpheader = [MessageFactory getHttpHeader];
    switch (params.count) {
        case 2:
            [req.body setItemParaListWithIndex:params[1], nil];
            break;
        case 3:
            [req.body setItemParaListWithIndex:params[1],params[2], nil];
            break;
        case 4:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3], nil];
            break;
        case 5:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4], nil];
            break;
        case 6:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5], nil];
            break;
        case 7:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6], nil];
            break;
        case 8:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7], nil];
            break;
        case 9:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8], nil];
            break;
        case 10:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9], nil];
            break;
        case 11:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10], nil];
            break;
        case 12:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11], nil];
            break;
        case 13:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11],params[12], nil];
            break;
        case 14:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11],params[12],params[13], nil];
            break;
        case 15:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11],params[12],params[13],params[14], nil];
            break;
        case 16:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6],params[7],params[8],params[9],params[10],params[11],params[12],params[13],params[14],params[15], nil];
            break;
        default:
            break;
    }
    WeakSelf_bb
    [MessageFactory doPost:req httpresult:^(ResponseMessage *res) {
        NSString *status = res.header.status;
        if ([status isEqualToString:@"200"]) {
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
            });
            success(res.body.data);
        }
        else{
            if (res.header.info) {
                weakSelf.failInfo = res.header.info;
            }
            failure(status,weakSelf.failInfo);
        }
    }];
}


- (void)requestDataNoHudWithParams:(NSArray *)params authType:(AuthModel)authType dataType:(DataType)dataType Success:(void (^)(id obj))success Failure:(void (^)(NSString *code,NSString *msg))failure{
    // 初始化请求体(params[0] -> 命令代码)
    NSArray *codeArray = [params[0] componentsSeparatedByString:@"/"];
    NSString *funcCode = [codeArray lastObject];
    [MessageFactory getAppConfig].appcode = [codeArray firstObject];
    RequestMessage *req = [[RequestMessage alloc] initWithFunc:funcCode];
    req.header.httpheader.device_token = [[NSUserDefaults standardUserDefaults] objectForKey:App_DeviceToken_Key];
    req.header.datatype = dataType;
    [MessageFactory getHttpHeader].authtype = authType;
    req.header.httpheader = [MessageFactory getHttpHeader];
    switch (params.count) {
        case 2:
            [req.body setItemParaListWithIndex:params[1], nil];
            break;
        case 3:
            [req.body setItemParaListWithIndex:params[1],params[2], nil];
            break;
        case 4:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3], nil];
            break;
        case 5:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4], nil];
            break;
        case 6:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5], nil];
            break;
        case 7:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6], nil];
            break;
        default:
            break;
    }
    WeakSelf_bb
    [MessageFactory doPost:req httpresult:^(ResponseMessage *res) {
        NSString *status = res.header.status;
        if ([status isEqualToString:@"200"]) {

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            
            success(res.body.data);
        }else{
            if (res.header.info) {
                self.failInfo = res.header.info;
            }
            NSLog(@"NetworkError:%@",self.failInfo);
            failure(status,weakSelf.failInfo);
        }
    }];
}

- (void)reportTraceDataWithParams:(NSArray *)params authType:(AuthModel)authType dataType:(DataType)dataType Success:(void (^)(id obj))success Failure:(void (^)(NSString *code,NSString *msg))failure{
    // 初始化请求体(params[0] -> 命令代码)
    NSArray *codeArray = [params[0] componentsSeparatedByString:@"/"];
    NSString *funcCode = [codeArray lastObject];
    [MessageFactory getAppConfig].appcode = [codeArray firstObject];
    RequestMessage *req = [[RequestMessage alloc] initWithFunc:funcCode];
    req.header.httpheader.device_token = [[NSUserDefaults standardUserDefaults] objectForKey:App_DeviceToken_Key];
    req.header.datatype = dataType;
    [MessageFactory getHttpHeader].authtype = authType;
    req.header.httpheader = [MessageFactory getHttpHeader];
    switch (params.count) {
        case 2:
            [req.body setItemParaListWithIndex:params[1], nil];
            break;
        case 3:
            [req.body setItemParaListWithIndex:params[1],params[2], nil];
            break;
        case 4:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3], nil];
            break;
        case 5:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4], nil];
            break;
        case 6:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5], nil];
            break;
        case 7:
            [req.body setItemParaListWithIndex:params[1],params[2],params[3],params[4],params[5],params[6], nil];
            break;
        default:
            break;
    }
    WeakSelf_bb
    [MessageFactory doPost:req httpresult:^(ResponseMessage *res) {
        NSString *status = res.header.status;
        if ([status isEqualToString:@"200"]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            success(res.body.data);
        }else{
            failure(status,weakSelf.failInfo);
        }
    }];
}

- (void)requestJavaBeanDataWithParams:(NSArray *)params authType:(AuthModel)authType dataType:(DataType)dataType Success:(void (^)(id obj))success Failure:(void (^)(NSString *code,NSString *msg))failure{
    // 初始化请求体(params[0] -> 命令代码)
    NSArray *codeArray = [params[0] componentsSeparatedByString:@"/"];
    NSString *funcCode = [codeArray lastObject];
    [MessageFactory getAppConfig].appcode = [codeArray firstObject];
    RequestMessage *req = [[RequestMessage alloc] initWithFunc:funcCode];
    req.header.httpheader.device_token = [[NSUserDefaults standardUserDefaults] objectForKey:App_DeviceToken_Key];
    req.header.datatype = dataType;
    [MessageFactory getHttpHeader].authtype = authType;
    [req.body setItemWithDictionary:params.lastObject];
    req.header.httpheader = [MessageFactory getHttpHeader];
    WeakSelf_bb
    [MessageFactory doPost:req httpresult:^(ResponseMessage *res) {
        NSString *status = res.header.status;
        if ([status isEqualToString:@"200"]) {

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            success(res.body.data);
            
        }else{
            if (res.header.info) {
                self.failInfo = res.header.info;
            }
            if (![status isEqualToString:@"309"]) {
                Show_Msg_Error(self.failInfo)
            }else{
                Dismiss_NoMsg
            }
            
            failure(status,weakSelf.failInfo);
        }
    }];
    
}

/**
 *  登录接口
 *
 *  @param params  参数数组
 *  @param success 成功回调
 *  @param failure 失败回调
 */
- (void)requestLoginWithParams:(NSArray *)params Success:(void (^)(UserInfoModel *model))success Failure:(void (^)(NSString *code,NSString *msg))failure{
    NSArray *codeArray = [API_App_User_Login componentsSeparatedByString:@"/"];
    NSString *funcCode = [codeArray lastObject];
    [MessageFactory getAppConfig].appcode = [codeArray firstObject];
    RequestMessage *req = [[RequestMessage alloc] initWithFunc:funcCode];
    //用户令牌
    NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:App_DeviceToken_Key];
    if (deviceToken && ![deviceToken isEqualToString:@""]) {
        req.header.httpheader.device_token = deviceToken;
    }
    
    NSMutableDictionary *dict = @{@"user_number":params.firstObject,
                           @"password":params.lastObject}.mutableCopy;
    [req.body setItemWithDictionary:dict];
    req.header.httpheader = [MessageFactory getHttpHeader];
    WeakSelf_bb
    [MessageFactory doPost:req httpresult:^(ResponseMessage *res) {
        NSString *status = res.header.status;
        if ([status isEqualToString:@"200"]){
            Show_Msg_Success(@"登陆成功")
            UserInfoModel *model = [UserInfoModel mj_objectWithKeyValues:res.body.data];
            //储存用户数据
            [[CacheTool sharedTool] setObject:model forKey:Cache_Bus_UserInfo];
            
            //改为登陆请求
            [MessageFactory getHttpHeader].authtype = AUTH_LOGIN;
            //设置登陆账号
            [[MessageFactory getHttpHeader] setAuth:model.account Password:model.password];
            success(model);
        }else{
            if (res.header.info) {
                self.failInfo = res.header.info;
            }
            
            if (![status isEqualToString:@"309"]) {
                NSString *failInfo = self.failInfo ? self.failInfo : @"请求失败";
                Show_Msg_Error(failInfo)
            }else{
                Dismiss_NoMsg
            }
            failure(status,weakSelf.failInfo);
        }
    }];
    
    
}

/**
 *  请求验证码接口
 *
 *  @param phoneNum 用户手机号
 *  @param success  成功回调
 *  @param failure  失败回调
 */
- (void)requestValidCodeWithPhoneNum:(NSString *)phoneNum type:(NSString *)type Success:(void (^)(id obj))success Failure:(void (^)(NSString *code,NSString *msg))failure{
    NSArray *codeArray = [API_App_GetValidCode componentsSeparatedByString:@"/"];
    NSString *funcCode = [codeArray lastObject];
    [MessageFactory getAppConfig].appcode = [codeArray firstObject];
    RequestMessage *req = [[RequestMessage alloc] initWithFunc:funcCode];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:phoneNum forKey:@"user_number"];
    [dict setObject:type forKey:@"type"];
    [req.body setItemWithDictionary:dict];
    req.header.httpheader = [MessageFactory getHttpHeader];
    Show_NoMsg
    WeakSelf_bb
    [MessageFactory doPost:req httpresult:^(ResponseMessage *res) {
        NSString *status = res.header.status;
        if ([status isEqualToString:@"200"]) {
            NSLog(@"%@...%@",res.header.status,res.body.data);
            [SVProgressHUD showSuccessWithStatus:res.header.info];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            success(res.body.data);
        }else{
            if (res.header.info) {
                self.failInfo = res.header.info;
            }
            
            if (![status isEqualToString:@"309"]) {
                NSString *failInfo = self.failInfo ? self.failInfo : @"请求失败";
                Show_Msg_Error(failInfo)
            }else{
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    Dismiss_NoMsg
                });
            }
            
            
            failure(status,weakSelf.failInfo);
        }
    }];
    
}


//- (void)uploadDeviceTokenWithParams:(NSArray *)params dataType:(DataType)dataType Success:(void (^)(id obj))success Failure:(void (^)())failure{
//    RequestMessage *req = [[RequestMessage alloc] initWithFunc:Bus_App_CatchDevice];
//    req.header.httpheader = [MessageFactory getHttpHeader];
//    [req.body setItemParaListWithIndex:params[0],params[1],params[2], nil];
//    [MessageFactory doPost:req httpresult:^(ResponseMessage *res) {
//        NSString *status = res.header.status;
//        if ([status isEqualToString:@"200"]) {
//            success(res.body.data);
//        }else{
//            NSLog(@"DeviceToken采集失败");
//        }
//    }];
//}


/**
 *  上传头像
 *
 *  @param params  参数
 *  @param success 成功回调
 *  @param failure 失败回调
 */
- (void)uploadIconImgWithParams:(NSArray *)params Img:(UIImage *)img Success:(void (^)(id obj))success Failure:(void (^)())failure{
    // 初始化请求体(params[0] -> 命令代码)
    NSArray *codeArray = [params[0] componentsSeparatedByString:@"/"];
    NSString *funcCode = [codeArray lastObject];
    [MessageFactory getAppConfig].appcode = [codeArray firstObject];
    RequestMessage *req = [[RequestMessage alloc] initWithFunc:funcCode];
    req.header.httpheader = [MessageFactory getHttpHeader];
    [MessageFactory getHttpHeader].authtype = AUTH_LOGIN;
    [req.body addImage:params[1] image:img];
    [MessageFactory doFormPost:req httpresult:^(ResponseMessage *res) {
        if ([res.header.status isEqualToString:@"200"]) {
            success(res.body.data);
        }else {
            failure(nil);
        }
        
        NSLog(@"上传头像结果\nstatus:%@,,info:%@",res.header.status,res.header.info);
    }];
}

- (void)uploadImageArray:(NSArray *)imageArray params:(NSArray *)params Success:(void (^)(id obj))success Failure:(void (^)())failure {
    // 初始化请求体(params[0] -> 命令代码)
    NSArray *codeArray = [params[0] componentsSeparatedByString:@"/"];
    NSString *funcCode = [codeArray lastObject];
    [MessageFactory getAppConfig].appcode = [codeArray firstObject];
    RequestMessage *req = [[RequestMessage alloc] initWithFunc:funcCode];
    req.header.httpheader = [MessageFactory getHttpHeader];
    [MessageFactory getHttpHeader].authtype = AUTH_LOGIN;
    req.body.media_list = [NSMutableArray arrayWithArray:imageArray];
    [MessageFactory doFormPost:req httpresult:^(ResponseMessage *res) {
        if ([res.header.status isEqualToString:@"200"]) {
            success(res.body.data);
        }else {
            failure(nil);
        }
    }];
}

//- (void)requestAppBaseConfigWithSuccess:(void (^)(NSString *url,NSString *version,NSString *versionDesc))success Failure:(void (^)())failure{
//    // 获取图片url前缀
//    [[NetworkTool sharedNetworkTool] requestDataWithParams:@[Globe_Arguments,@"iphone",@""] Success:^(ResponseMessage *res) {
//        NSArray *arr = [res.body getItemsArray];
//        // 获取图片地址前缀
//        NSDictionary *dict = arr[0];
//        NSString *url = dict[@"paravalue"];
//        [GlobalModel sharedGlobalModel].iconUrlPrefix = url;
//        NSLog(@"获取图片地址前缀成功:%@",url);
//        
//        // 获取AppStore版本对应信息
//        NSDictionary *versionDict = arr[1];
//        NSString *versionNum = versionDict[@"paravalue"];
//        NSString *versionDesc = versionDict[@"para_desc"];
//        [GlobalModel sharedGlobalModel].versionNum = versionNum;
//        [GlobalModel sharedGlobalModel].versionDesc = versionDesc;
//        NSLog(@"AppStore版本:%@ AppStore描述:%@",versionNum,versionDesc);
//        if (success) {
//            success(url,versionNum,versionDesc);
//        }
//    } Failure:^(ResponseMessage *res) {
//        if (failure) {
//            failure();
//        }
//    }];
//}
@end
